﻿#region zh-CHS 2006 - 2007 DemoSoft 团队 | en 2006 - 2007 DemoSoft Team

//     NOTES
// ---------------
//
// This file is a part of the G.O.S.E(Game Online Server Engine) for .NET.
//
//                 2006-2007 DemoSoft Team
//
//
// First Version : by H.Q.Cai - mailto:caihuanqing@hotmail.com

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published
 *   by the Free Software Foundation; either version 2.1 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

#region zh-CHS 包含名字空间 | en Include namespace
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Demo_G.O.S.E.ServerEngine.Util;
using Demo_G.O.S.E.ServerEngine.World;
using Demo_G.O.S.E.ServerEngine.Common;
using Demo_G.O.S.E.ServerEngine.Network.DLL;
#endregion

namespace Demo_G.O.S.E.ServerEngine.Network
{
    /// <summary>
    /// 服务端监听
    /// </summary>
    [MultiThreadedSupportgAttribute( "当前的类所有成员都可锁定,支持多线程操作" )]
    public class Listener : IDisposable
    {
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 监听到的客户端
        /// </summary>
        private Queue<ClientSocketHandler> m_Accepted   = new Queue<ClientSocketHandler>();
        /// <summary>
        /// 监听到的客户端的锁
        /// </summary>
        private ReaderWriterLockSlim m_LockAccepted = new ReaderWriterLockSlim();
        #endregion

        #region zh-CHS 构造和初始化和清理 | en Constructors and Initializers and Dispose
        /// <summary>
        /// 初始化构造
        /// </summary>
        public Listener()
        {
            m_SocketServer.ThreadEventAcceptor += new EventDelegateAcceptor( OnAcceptor );
        }

        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 是否已经处理过断开
        /// </summary>
        private long m_bIsDisposed = 0;
        #endregion
        /// <summary>
        /// 断开
        /// </summary>
        public void Dispose()
        {
            if ( Interlocked.Exchange( ref m_bIsDisposed, 1 ) == 0 && m_SocketServer != null )
            {
                try
                {
                    m_SocketServer.StopServer();
                }
                catch
                {
                    Debug.WriteLine( "Listener.Dispose(...) - m_SocketMainServer.StopServer(...) Exception error!" );
                }

                m_SocketServer = null;
            }
        }
        #endregion

        #region zh-CHS 共有属性 | en Public Properties
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 主监听处理
        /// </summary>
        private SocketServer m_SocketServer = new SocketServer();
        #endregion
        /// <summary>
        /// 监听的主处理
        /// </summary>
        public SocketServer ListenerSocket
        {
            get { return m_SocketServer; }
        }

        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 管理当前的世界服务
        /// </summary>
        private BaseWorld m_BaseWorld = null;
        #endregion
        /// <summary>
        /// 管理当前的世界服务
        /// </summary>
        public BaseWorld BaseWorld
        {
            get { return m_BaseWorld; }
        }

        #region zh-CHS BaseWorld 方法 | en BaseWorld Method
        /// <summary>
        /// 设置管理当前的世界服务
        /// </summary>
        /// <param name="baseWorld"></param>
        internal void SetBaseWorld( BaseWorld baseWorld )
        {
            m_BaseWorld = baseWorld;
        }
        #endregion

        #endregion

        #region zh-CHS 共有方法 | en Public Methods
        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public bool StartServer( int port )
        {
            if ( m_SocketServer.IsConnected == true )
            {
                Debug.WriteLine( "Listener.StartServer(...) - m_SocketServer.IsConnected == true error!" );
                return false;
            }

            if ( m_SocketServer.StartServer( port ) )
            {
                LOGs.WriteLine( LogMessageType.MSG_NOTICE, "新监听： 端口 {0} ", port );

                Interlocked.Exchange( ref m_bIsDisposed, 0 );
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="strHostNamePort">地址和端口</param>
        /// <returns></returns>
        public bool StartServer( string strHostNamePort )
        {
            if ( m_SocketServer.IsConnected == true )
            {
                Debug.WriteLine( "Listener.StartServer(...) - m_SocketServer.IsConnected == true error!" );
                return false;
            }

            if ( m_SocketServer.StartServer( strHostNamePort ) )
            {
                LOGs.WriteLine( LogMessageType.MSG_NOTICE, "新监听： 地址 {0} ", strHostNamePort );

                Interlocked.Exchange( ref m_bIsDisposed, 0 );
                return true;
            }
            else
                return false;
        }
        #endregion

        #region zh-CHS 内部方法 | en Internal Method
        #region zh-CHS 私有静态成员变量 | en Private Static Member Variables
        /// <summary>
        /// 空的ClientSocketHandler数组
        /// </summary>
        private static ClientSocketHandler[] s_EmptySockets = new ClientSocketHandler[0];
        #endregion
        /// <summary>
        /// 获取新的联接过来的客户端
        /// </summary>
        /// <returns></returns>
        internal ClientSocketHandler[] Slice()
        {
            ClientSocketHandler[] arrayReturn = s_EmptySockets;

            ReaderWriterLockSlimEx.EnterWriteLock( m_LockAccepted );
            do
            {
                if ( m_Accepted.Count <= 0 )
                    break;

                arrayReturn = m_Accepted.ToArray();

                // 清空数据,让它的调用着来处理这些数据
                m_Accepted.Clear();
            } while ( false );
            ReaderWriterLockSlimEx.ExitWriteLock( m_LockAccepted );

            return arrayReturn;
        }

        /// <summary>
        /// 释放指定的客户端到内存池里面
        /// </summary>
        /// <param name="clientSocketHandler"></param>
        internal void Free( ClientSocketHandler clientSocketHandler )
        {
            // 返回至内存池(ClientSocketHandler)
            m_ClientSocketHandlerPool.ReleasePoolContent( clientSocketHandler );
        }
        #endregion

        #region zh-CHS 私有的事件处理函数 | en Private Event Handlers
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 主要是需要保留ClientSocketHandler.ReceiveBuffer
        /// </summary>
        private ProcessMessageBlockPool<ClientSocketHandler> m_ClientSocketHandlerPool = new ProcessMessageBlockPool<ClientSocketHandler>( "Listener - ClientSocketHandler", 1024 );
        #endregion
        /// <summary>
        /// 连接新的客户端的处理
        /// </summary>
        /// <param name="NonceClientHandler"></param>
        /// <param name="AllHandlerManager"></param>
        /// <param name="ClientHandlerAtServer"></param>
        private void OnAcceptor( ServiceHandle nonceClientHandler, ServiceHandleManager allHandlerManager, out ServiceHandle clientHandlerAtServer )
        {
            clientHandlerAtServer = null;

            SocketConnectEventArgs socketConnectEventArgs = new SocketConnectEventArgs( nonceClientHandler );
            EventSink.InvokeSocketConnect( socketConnectEventArgs );

            // 如果允许连接
            if ( socketConnectEventArgs.AllowConnection )
            {
                ServiceHandle newClientHandlerAtServer = new ServiceHandle();
                if ( newClientHandlerAtServer == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - newClientHandlerAtServer == null error!" );

                    return;
                }
                newClientHandlerAtServer.Value = nonceClientHandler.Value;


                ServiceHandleManager newSocketHandlerManager = new ServiceHandleManager();
                if ( newSocketHandlerManager == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - newSocketHandlerManager == null error!" );

                    return;
                }
                newClientHandlerAtServer.SocketHandlerManager = newSocketHandlerManager;
                newClientHandlerAtServer.SocketHandlerManager.Value = allHandlerManager.Value;


                ClientSocketHandler newClientSocketHandler = m_ClientSocketHandlerPool.AcquirePoolContent();
                if ( newClientSocketHandler == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - newClientSocketHandler == null error!" );

                    return;
                }
                newClientSocketHandler.InitClientHandler( this, newClientHandlerAtServer );


                // out ServiceHandle
                clientHandlerAtServer = newClientHandlerAtServer;

                ReaderWriterLockSlimEx.EnterWriteLock( m_LockAccepted );
                {
                    m_Accepted.Enqueue( newClientSocketHandler );
                }
                ReaderWriterLockSlimEx.ExitWriteLock( m_LockAccepted );

                LOGs.WriteLine( LogMessageType.MSG_INFO, "新连接: {0}  [在线连接数 {1}] [总连接数 {2}]", nonceClientHandler.ClientAddress, allHandlerManager.OnlineClientCount, allHandlerManager.ClientCount );

                // 有新的连接过来需要发送全局信号处理新的连接
                if ( m_BaseWorld != null )
                    m_BaseWorld.SetWorldSignal();
                else
                    Debug.WriteLine( "Listener.OnAcceptor(...) - m_BaseWorld == null error!" );
            }
            else // 不允许连接
            {
                try
                {
                    nonceClientHandler.CloseSocket();
                }
                catch
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - NonceClientHandler.CloseSocket(...) Exception error!" );
                }

                LOGs.WriteLine( LogMessageType.MSG_WARNING, "新连接: {0} 无法通过验证被断开! [在线连接数 {1}] [总连接数 {2}]", nonceClientHandler.ClientAddress, allHandlerManager.OnlineClientCount, allHandlerManager.ClientCount );
            }
        }
        #endregion
    }
}
#endregion

